#include "datacollect.h"

const qint64 cmd_dataCollectionStart = 222;
const qint64 cmd_dataCollectionStop = 333;
const qint64 cmd_faultDiagnosis = 444;
QString FileName = "./test.txt";


DataCollect::DataCollect(QObject *parent) : QObject(parent)
{
    var_dataCollectTimer = new QTimer(this);
    var_dataCollectTimer->setTimerType(Qt::PreciseTimer);
    connect(var_dataCollectTimer,&QTimer::timeout,this,&DataCollect::dataCollection);
}

DataCollect::~DataCollect()
{
    delete var_dataFiles;
    delete var_dataCollectTimer;
}

void DataCollect::dataCollectionControl(const qint64 cmd)
{
    if(cmd == cmd_dataCollectionStart)
    {
        qDebug("data collect start......");
        var_dataFiles = new QFile(FileName);
        if(!var_dataFiles->open(QIODevice::WriteOnly))
        {
            var_dataFiles->close();
            qDebug("file open failed!!!!");
            delete var_dataFiles;

            emit dataCollectInfo("数据采集失败\n可能是采集文件创建失败");
            return;
        }

        var_dataCollectTimer->setInterval(10);
        var_dataCollectTimer->start();
        emit dataCollectInfo("数据采集开始");
    }
    else
    {
        qDebug("data collect finish");
        var_dataCollectTimer->stop();
        var_dataFiles->close();
        delete var_dataFiles;
        var_dataFiles = nullptr;

        emit dataCollectFinish();
    }
}

void DataCollect::dataCollection()
{
    static uint64_t num = 0;
    if(var_dataFiles != nullptr)
    {
        QByteArray arry;
        for (int var = 0; var < 999; ++var)
        {
            const char* data = QString(QString::number(++num)+"\n").toLatin1().constData();
            arry.append(data);
        }
        var_dataFiles->write(arry);
    }
}
